<template>
  <el-row>
    <el-card>
      <el-button-group>
        <el-button
          v-for="(item, index) in $t('collectionManagement.report.groupType')"
          :key="index"
          :type="chType === item['value'] ? 'primary' : ''"
          @click="changeStatus(item['value'])"
        >
          {{ item['desc'] }}
        </el-button>
      </el-button-group>
      <el-divider />
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item :label="$t('collectionManagement.report.data.time')">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item v-if="!stageId" :label="$t('collectionManagement.report.data.stage')">
          <el-select v-model="searchForm.stageId" clearable :placeholder="$t('collectionManagement.report.prompt.stage')">
            <el-option
              v-for="item in allStage"
              :key="item.id"
              :label="item.phaseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.report.data.reBorrow')">
          <el-select v-model="searchForm.firstLoan" clearable :placeholder="$t('collectionManagement.report.prompt.select')">
            <el-option
              v-for="item in $t('collectionManagement.report.borrowData')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!firmId" :label="$t('collectionManagement.report.data.company')">
          <el-select v-model="searchForm.firmId" clearable :placeholder="$t('collectionManagement.management.prompt.company')">
            <el-option
              v-for="item in allFirm"
              :key="`${item.id}_firm`"
              :label="item['firmName']"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!groupId" :label="$t('collectionManagement.report.data.group')">
          <el-select v-model="searchForm.groupId" clearable :placeholder="$t('collectionManagement.management.prompt.group')">
            <el-option-group
              v-for="group in allGroup"
              :key="group.value"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.report.data.commissioner')">
          <el-cascader
            v-model="searchForm.staffId"
            clearable
            :options="allStaff"
            :props="{ expandTrigger: 'hover' }"
            :placeholder="$t('collectionManagement.report.prompt.commissioner')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.report.data.productType')">
          <el-select v-model="searchForm.loanProductType" clearable :placeholder="$t('collectionManagement.report.prompt.productType')">
            <el-option
              v-for="item in $t('collectionManagement.report.type')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="exportList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%"
      >
        <el-table-column
          v-if="chType === 2"
          fixed="left"
          prop="date"
          :label="tableText['date']"
          min-width="170"
        />
        <el-table-column
          fixed="left"
          prop="username"
          :label="tableText['account']"
          min-width="150"
        />
        <el-table-column
          fixed="left"
          prop="staffName"
          :label="tableText['name']"
          min-width="150"
        />
        <el-table-column
          prop="groupName"
          :label="tableText['group']"
          min-width="150"
        />
        <el-table-column
          prop="firmName"
          :label="tableText['company']"
          min-width="150"
        />
        <el-table-column
          prop="todayFinishCaseCount"
          :label="tableText['casesNumberTodaySuccess']"
          min-width="170"
        >
          <template slot-scope="scope">
            {{ scope.row['todayFinishCaseCount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="todayFinishCaseAmount"
          :label="tableText['recallTotalToday']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['todayFinishCaseAmount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="beforCount"
          :label="tableText['beforeStayNumber']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['beforCount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="todayAddedCaseCount"
          :label="tableText['addCasesNumberToday']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['todayAddedCaseCount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="todayAddedCaseAmount"
          :label="tableText['addRecallTotalToday']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['todayAddedCaseAmount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="allotOtherCount"
          :label="tableText['distribution']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['allotOtherCount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="todayUrgentRecallCount"
          :label="tableText['needCasesNumber']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['todayUrgentRecallCount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currentAllocationCaseCount"
          :label="tableText['currentCasesNumber']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['currentAllocationCaseCount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currentAllocationCaseAmount"
          :label="tableText['currentRecallTotal']"
          min-width="180"
        >
          <template slot-scope="scope">
            {{ scope.row['currentAllocationCaseAmount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="keepCaseCount"
          :label="tableText['retainCasesNumber']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row['keepCaseCount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="keepCaseAmount"
          :label="tableText['retainRecallTotal']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row['keepCaseAmount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="failCaseCount"
          :label="tableText['failCasesNumber']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row['failCaseCount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="failCaseAmount"
          :label="tableText['failRecallTotal']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row['failCaseAmount'] || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="urgentRecallSuccessRatio"
          :label="tableText['recallRate']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row['urgentRecallSuccessRatio'] !== null ? (scope.row['urgentRecallSuccessRatio'] * 100).toFixed(2) + '%' : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="urgentRecallFailRatio"
          :label="tableText['failureRate']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row['urgentRecallFailRatio'] !== null ? (scope.row['urgentRecallFailRatio'] * 100).toFixed(2) + '%' : 0 }}
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </el-row>
</template>

<script>
import { getBusinessConfig, getAllOverdueFirm, getAllOverdueStaff, getAllOverdueGroup, getUrgentRecallGroupStatementTotal, exportUrgentRecallGroupStatementTotal, getUrgentRecallGroupStatementDetail, exportUrgentRecallGroupStatementDetail } from '@/api/collection'
import { formatDate } from '@/utils/method'
export default {
  name: 'GroupReport',
  props: {
    firmId: {
      type: Number,
      default: null
    },
    groupId: {
      type: Number,
      default: null
    },
    stageId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      loading: true,
      chType: 1,
      time: [new Date(), new Date()],
      allStage: [],
      allFirm: [],
      allStaff: [],
      staffData: [],
      allGroup: [],
      tableData: [],
      tableText: {},
      totalNumber: 0,
      searchForm: this.params()
    }
  },
  mounted() {
    this.searchForm.groupId = this.groupId !== null ? this.groupId - 0 : null
    this.searchForm.firmId = this.firmId !== null ? this.firmId - 0 : null
    this.searchForm.stageId = this.stageId !== null ? this.stageId - 0 : null
    this.tableText = this.$t('collectionManagement.report.table')
    this.getAllStage()
    this.getAllFirm()
    setTimeout(() => {
      this.getData()
    }, 10)
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        queryStartTime: null,
        queryEndTime: null,
        stageId: '',
        firstLoan: '',
        loanProductType: '',
        firmId: null,
        groupId: null,
        staffId: []
      }
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.time = [new Date(), new Date()]
      this.searchForm = this.params()
      this.getData()
    },
    changeStatus(type) {
      this.chType = type
      this.getData()
    },
    getAllStage() {
      const data = {
        isPage: false
      }
      getBusinessConfig(data)
        .then(res => {
          if (res.success) {
            this.allStage = res.data.filter(item => {
              return item['state'] === 'ACTIVATE'
            })
            const obj = [{
              phaseName: this.$t('common.all'),
              id: ''
            }]
            this.allStage = obj.concat(this.allStage)
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getAllFirm() {
      getAllOverdueFirm()
        .then(res => {
          if (res.success) {
            this.allFirm = res.data.filter(item => {
              return item['status'] === 2
            })
            this.getAllGroup()
            this.getAllStaff()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getAllStaff() {
      const data = {
        isPage: false
      }
      getAllOverdueStaff(data)
        .then(res => {
          if (res.success) {
            let arr = res.data
            if (this.firmId) {
              arr = arr.filter(item => {
                return item['firmId'] === this.firmId && item['groupId'] === this.groupId
              })
            }
            // .filter(item => {
            // return item['status'] === 2
            // })
            const option = []
            arr.forEach(item => {
              if (!option.includes(item['firmName'])) {
                option.push(item['firmName'])
              }
            })
            const optionData = []
            option.forEach((v, i) => {
              const children = []
              const a = arr.filter(item => {
                return item['firmName'] === v
              })
              const arr1 = []
              a.forEach(item => {
                if (!arr1.includes(item['groupName'])) {
                  arr1.push(item['groupName'])
                }
              })
              arr1.forEach((f, index) => {
                const b = a.filter(item => {
                  return item['groupName'] === f
                })
                const grand = []
                b.forEach(grandson => {
                  grand.push({
                    label: grandson['staffName'],
                    value: grandson['id']
                  })
                })
                children.push(
                  {
                    label: f,
                    value: `groupName${index}`,
                    children: grand
                  }
                )
              })
              optionData.push({
                label: v,
                value: i,
                children: children
              })
            })
            this.allStaff = optionData
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getAllGroup() {
      getAllOverdueGroup()
        .then(res => {
          if (res.success) {
            this.allGroup = res.data.filter(item => {
              return item['status'] === 2
            })
            const arr = []
            this.allGroup.map(item => {
              if (!arr.includes(item['firmId'])) {
                arr.push(item['firmId'])
              }
            })
            const group = []
            if (arr.length > 0) {
              arr.forEach(v => {
                const options = []
                const a = this.allGroup.filter(item => {
                  return item['firmId'] === v
                })
                a.forEach(item => {
                  options.push(
                    {
                      label: item['groupName'],
                      value: item['id']
                    }
                  )
                })
                const name = this.allFirm.filter(aa => {
                  return aa['id'] === v
                })
                const firmName = name && name[0] && name[0]['firmName'] ? name[0]['firmName'] : 0
                group.push({
                  label: firmName,
                  value: firmName,
                  options
                })
              })
            }
            this.allGroup = group
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    searchData() {
      const data = {
        queryStartTime: this.searchForm.queryStartTime,
        queryEndTime: this.searchForm.queryEndTime,
        stageId: this.searchForm.stageId,
        firstLoan: this.searchForm.firstLoan,
        loanProductType: this.searchForm.loanProductType,
        groupId: this.searchForm.groupId,
        staffId: this.searchForm.staffId.length > 0 ? this.searchForm.staffId[2] : [],
        pageSize: this.searchForm.pageSize,
        currentPage: this.searchForm.currentPage
      }
      if (this.time && this.time.length > 0) {
        data['queryStartTime'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['queryEndTime'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      }
      return data
    },
    getData() {
      if (this.chType === 1) {
        this.loading = true
        getUrgentRecallGroupStatementTotal(this.searchData())
          .then(res => {
            this.loading = false
            if (res.success) {
              this.tableData = res.data
              this.totalNumber = res.page ? res.page['totalNumber'] : 0
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.loading = false
            this.$message.error(err.message)
          })
      } else {
        getUrgentRecallGroupStatementDetail(this.searchData())
          .then(res => {
            this.loading = false
            if (res.success) {
              this.tableData = res.data
              this.totalNumber = res.page ? res.page['totalNumber'] : 0
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.loading = false
            this.$message.error(err.message)
          })
      }
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    exportList() {
      if (this.chType === 1) {
        exportUrgentRecallGroupStatementTotal(this.searchData())
      } else {
        exportUrgentRecallGroupStatementDetail(this.searchData())
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
</style>
